package gw.com.android.ui;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.gwtsz.gts2.hx.R;

import java.io.File;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.app.dispatch.AppDispatch;
import gw.com.android.model.ConfigSettingDeal;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.ui.dialog.SharePopWindow;
import gw.com.android.ui.views.NoticeView;
import gw.com.android.utils.ImageUtil;
import gw.com.android.utils.PackStatis;
import www.com.library.app.FragmentsManagerUtil;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.view.BtnClickListener;
import www.com.library.view.RecyclerClickListener;

/**
 * 公共嵌入url界面
 *
 * @author reeta
 */
public class WebPageActivity extends BaseActivity implements PlatformActionListener {
    /**
     * 嵌入页面的URL地址
     */
    protected String url;
    /**
     * 显示的标题
     */
    public static String showTitle;
    /**
     * 显示title bar 最左边的文字
     */
    protected String leftTxt;
    /**
     * 嵌入网站类型
     */
    protected String key;
    /**
     * 判断是否需要用到单点登录
     */
    protected boolean hasLogin;
    /**
     * 顶部的Title bar
     */
    public String mCurrentTag = AppContances.TAB_ID_WEBPAGE;
    private WebFragment mWebPageFragment;
    private LoginWebFragment mLoginWebPageFragment;
    private DataItemDetail mItem;
    private SharePopWindow mSharePopwindow;//分享功能弹层
    private LinearLayout mContentLayout;
    private RelativeLayout mRlShare;
    private ImageView mIvShare;
    private SharePopWindow mSharePopWindow;

    @Override
    protected void setAcitivityParam() {
        if (getIntent() != null) {
            mItem = getIntent().getParcelableExtra("mItem");
            leftTxt = getIntent().getStringExtra("left_title");
        }
//		Logger.e("WebPageActivity","--------------"+mItem.toJsonString());
        key = mItem.getString(ConfigType.CONFIG_TYPE_KEY_TAG);
        hasLogin = mItem.getString(ConfigType.CONFIG_TYPE_TYPE_TAG).equals(ConfigType.CONFIG_TYPE_TYPE_URL_RGS_TAG);
        showTitle = mItem.getString(ConfigType.CONFIG_TYPE_TITLE_TAG);
        String urlString = mItem.getString(ConfigType.CONFIG_TYPE_TYPE_URL_TAG);
        if (AppDispatch.dispatch(this, urlString)) {
            finish();
        }
    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_webview_page;
    }

    @Override
    protected void initLayoutView() {
        mContentLayout = (LinearLayout) findViewById(R.id.main_trade_table);
        mRlShare = (RelativeLayout) findViewById(R.id.rl_share);
        mIvShare = (ImageView) findViewById(R.id.iv_share);
        if (key.equals(ConfigType.REPORT_TAG) && showTitle.length() > 2) {
            //报表相关界面title处理
            showTitle = showTitle.substring(2, showTitle.length());
        }
        if (key.length() < 1 || key.equals(ConfigType.ADS_DETAIL_TAG) || key.equals(ConfigType.FAQ_SUB_TAG)) {
            url = mItem.getString(ConfigType.CONFIG_TYPE_TYPE_URL_TAG);
        } else {
            url = ConfigUtil.instance().getUrlPath(key);
            url = inspectParam(url, mItem);
        }
        Logger.e("网页加载地址 ： url = " + url);

        mTitleBar.setAppTitle(showTitle);
        mTitleBar.setLeftSendaryIcon(R.mipmap.a_nav_close);
        setBtnListener();
        //右上角按钮逻辑处理
        if (key.equals(ConfigType.QUOTE_CONTACT_TAG) || key.equals(ConfigType.MY_CONTACT_TAG)
                || key.equals(ConfigType.HOME_CONTACT_TAG)) {
            //客服
            if (ConfigUtil.instance().customerFunction() == 2) {
                mTitleBar.setRightIcon(R.mipmap.a_nav_onlinecall);
            }
        } else if (key.equals(ConfigType.ADS_DETAIL_TAG) && ConfigUtil.instance().hasShareFunction()) {
            //分享
//            mTitleBar.setRightIcon(R.mipmap.a_nav_sharenews);
        } else if (key.equals(ConfigType.QQ_SERVICE_TAG)) {
            mTitleBar.setRightIcon(R.mipmap.a_nav_phone);
        } else if (key.equals(ConfigType.DEPOSIT_TAG)) {//充值？
//            new AssistantDialog().attach(this, mTitleBar, AssistantDialog.DEPOSIT);//弹窗，但是现在不需要弹窗，直接显示客服ICON即可

            mTitleBar.setRightIcon(R.mipmap.a_nav_service_b);
//            showNoticeView();//这是那个走马灯
        } else if (mItem.getString(ConfigType.CONFIG_TYPE_VALUE_TAG).equals("profitAndLossRecord")) {
//            mTitleBar.setRightIcon(R.mipmap.a_nav_share);
        } else {
            //mTitleBar.setRightButton(false);
        }

        if (hasLogin) {
            showLoginWebViewFragment();
        } else {
            showWebViewFragment();
        }
    }

    private void showNoticeView() {
        FrameLayout container = (FrameLayout) findViewById(R.id.fl_noticeview_container);
        NoticeView noticeView = new NoticeView(this);
        container.addView(noticeView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    private String inspectParam(String url, DataItemDetail item) {
        if (TextUtils.isEmpty(url)) {
            return url;
        }
        String param = item.getString(ConfigType.CONFIG_TYPE_TYPE_URL_PARAMS_TAG);
        if (!TextUtils.isEmpty(param)) {
            int index = url.indexOf("?");
            if (index < 0) {
                if (url.endsWith("/")) {
                    url = url.substring(0, url.length() - 1);
                }
                url += "?" + param;
            } else {
                if (url.length() < index + 1) {
                    return url;
                }
                String left = url.substring(0, index + 1);
                String right = url.substring(index + 1, url.length());
                url = left + param + "&" + right;
            }
        }
        return url;
    }

    private boolean ifCloseShare = true;

    /**
     * 界面顶部按钮点击事件处理
     */
    public void setBtnListener() {
        mTitleBar.setBtnClickListener(new BtnClickListener() {
            @Override
            public void onBtnClick(int viewID) {
                if (viewID == R.id.title_right_icon) {
                    if (key.equals(ConfigType.ADS_DETAIL_TAG)) {
                        if (null == mSharePopwindow) {
                            if (ifCloseShare)
                                return;
                            mSharePopwindow = new SharePopWindow(WebPageActivity.this, AppContances.SHARE_ADS_TYPE, null, mItem, new RecyclerClickListener() {
                                @Override
                                public void onClick(final int position, DataItemDetail itemDetail) {
                                    final String mUrl = url;
                                    Logger.e("分享详情连接：url == " + mUrl);
                                    if (mSharePopwindow.getTitleId(position) == R.string.app_share_copy) {
                                        copy(mUrl, WebPageActivity.this);
                                        showToastPopWindow(AppMain.getAppString(R.string.app_share_copy_success));
                                    } else {
                                        mSharePopwindow.onShareFun(mSharePopwindow.getTitleId(position),
                                                showTitle,
                                                "",
                                                mUrl, WebPageActivity.this);
                                    }
                                }
                            });
                        }
                        mSharePopwindow.show();
                    } else if (key.equals(ConfigType.QUOTE_CONTACT_TAG) || key.equals(ConfigType.MY_CONTACT_TAG)
                            || key.equals(ConfigType.HOME_CONTACT_TAG)) {
                        ConfigSettingDeal mDeal = new ConfigSettingDeal();
                        mDeal.openQQ(WebPageActivity.this);
                    } else if (key.equals(ConfigType.QQ_SERVICE_TAG)) {
                        String phoneValue = ConfigUtil.instance().mConfigObject.optString("phoneValue");
                        ConfigSettingDeal.showCallDialog(WebPageActivity.this, phoneValue);
                    } else if (mItem.getString(ConfigType.CONFIG_TYPE_VALUE_TAG).equals("profitAndLossRecord")) {
                        mContentLayout.setDrawingCacheEnabled(true);
                        mContentLayout.buildDrawingCache();
                        Bitmap bitmap = Bitmap.createBitmap(mContentLayout.getDrawingCache());
                        mContentLayout.setDrawingCacheEnabled(false);
                        mIvShare.setImageBitmap(bitmap);
                        mRlShare.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mRlShare.setDrawingCacheEnabled(true);
                                mRlShare.buildDrawingCache();
                                Bitmap qrBitmap = Bitmap.createBitmap(mRlShare.getDrawingCache());
                                mRlShare.setDrawingCacheEnabled(false);
                                Bitmap adBitmap = ImageUtil.getAdvertiseShareBitmap(qrBitmap.getWidth());
                                Bitmap mergedBitmap = ImageUtil.mergeImageVertical(qrBitmap, adBitmap);
                                final File file = ImageUtil.saveImage(mergedBitmap, GTConfig.instance().getRootDirectory());
                                adBitmap.recycle();
                                mergedBitmap.recycle();
                                if (null == mSharePopWindow) {
                                    if (ifCloseShare)
                                        return;
                                    mSharePopWindow = new SharePopWindow(WebPageActivity.this, AppContances.SHARE_IMAGE_TYPE, mTitleBar, null, new RecyclerClickListener() {
                                        @Override
                                        public void onClick(int position, DataItemDetail itemDetail) {
                                            mSharePopWindow.onShareFun(mSharePopWindow.getTitleId(position),
                                                    "", "", "", file.getAbsolutePath(), new PlatformActionListener() {
                                                        @Override
                                                        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                                                            showToastPopWindow(AppMain.getAppString(R.string.app_share_success));
                                                        }

                                                        @Override
                                                        public void onError(Platform platform, int i, Throwable throwable) {
                                                            showToastPopWindow(AppMain.getAppString(R.string.app_share_fail) + throwable.getMessage());
                                                        }

                                                        @Override
                                                        public void onCancel(Platform platform, int i) {
                                                            showToastPopWindow(AppMain.getAppString(R.string.app_share_cancel));
                                                        }
                                                    });
                                        }
                                    });
                                }
                                mSharePopWindow.show();
                            }
                        }, 1);
                    } else if (key.equals(ConfigType.DEPOSIT_TAG)) {
                        ConfigSettingDeal mDeal = new ConfigSettingDeal();
                        mDeal.openQQ(WebPageActivity.this, ConfigType.QQ_SOURCE_LOGIN);
                    }
                } else if (viewID == R.id.title_left_icon) {
                    onBackPressed();
                } else if (viewID == R.id.title_left_secondary_icon) {
                    if (!handleFromAd()) {
                        finish();
                    }
                }
            }
        });
    }

    /**
     * 实现文本复制功能
     *
     * @param content
     */
    public void copy(String content, Context context) {
        // 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content.trim());
    }

    @Override
    protected void initViewData() {

    }

    /**
     * 返回bundle对象
     */
    private Bundle getBundle() {
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        bundle.putString(ConfigType.CONFIG_TYPE_KEY_TAG, key);
        bundle.putParcelable("item", mItem);
        return bundle;
    }

    /**
     * 展示普通的网页嵌套界面
     */
    public void showWebViewFragment() {
        mWebPageFragment = (WebFragment) FragmentsManagerUtil.instance().getFragmentbyTag(WebPageActivity.this, mCurrentTag);
        if (null == mWebPageFragment) {
            mWebPageFragment = new WebFragment();
            mWebPageFragment.setArguments(getBundle());
            FragmentsManagerUtil.instance().addPushMsgTabFragment(WebPageActivity.this, mWebPageFragment, mCurrentTag);
        }
        showFragment(mWebPageFragment);
    }

    /**
     * 展示需要使用到单点登录界面的网页嵌套界面
     */
    public void showLoginWebViewFragment() {
        mLoginWebPageFragment = (LoginWebFragment) FragmentsManagerUtil.instance().getFragmentbyTag(WebPageActivity.this, mCurrentTag);
        if (null == mLoginWebPageFragment) {
            mLoginWebPageFragment = new LoginWebFragment();
            mLoginWebPageFragment.setArguments(getBundle());
            FragmentsManagerUtil.instance().addPushMsgTabFragment(WebPageActivity.this, mLoginWebPageFragment, mCurrentTag);
        }
        showFragment(mLoginWebPageFragment);
    }

    @Override
    public void onBackPressed() {
        if (mWebPageFragment != null && mWebPageFragment.onBackPressed()) {
            return;
        }
        if (mLoginWebPageFragment != null && mLoginWebPageFragment.onBackPressed()) {
            return;
        }
        if (handleFromAd()) {
            return;
        }
        super.onBackPressed();
    }

    private boolean handleFromAd() {
        if (getIntent().getBooleanExtra("fromAd", false)) {
            if (getIntent().getBooleanExtra("awake", false)) {
                finish();
                return true;
            }
            // 从广告页进入
            if (getIntent().getExtras() != null && getIntent().getIntExtra("where", 0) == AppContances.TYPE_FORM_NOTIFY) {
                // 来自于推送
                PackStatis.getToService(PackStatis.EventAction.START.getValue(), PackStatis.EventCategory.MAIN.getValue(), null, "2");
                ActivityManager.showMainTab(this, ConfigType.TAB_HOME_TAG, getIntent().getExtras());
            } else {
                PackStatis.getToService(PackStatis.EventAction.START.getValue(), PackStatis.EventCategory.MAIN.getValue(), null, "1");
                ActivityManager.showMainTab(this, ConfigType.TAB_HOME_TAG, 0);
            }
            finish();
            return true;
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //广告详情需要进行分享操作
        if (null != mShareHandler) {
            mShareHandler.removeCallbacksAndMessages(null);
            mShareHandler = null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private Handler mShareHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case AppContances.HANDLER_SHARE_SUCCESS:
                    showToastPopWindow(AppMain.getAppString(R.string.app_share_success));
                    break;
                case AppContances.HANDLER_SHARE_CANCEL:
                    showToastPopWindow(AppMain.getAppString(R.string.app_share_cancel));
                    break;
                case AppContances.HANDLER_SHARE_FAIL:
                    showToastPopWindow(AppMain.getAppString(R.string.app_share_fail) + msg.obj);
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        mShareHandler.sendEmptyMessage(AppContances.HANDLER_SHARE_SUCCESS);
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        throwable.printStackTrace();
        Message msg = new Message();
        msg.what = AppContances.HANDLER_SHARE_FAIL;
        msg.obj = throwable.getMessage();
        mShareHandler.sendMessage(msg);
    }

    @Override
    public void onCancel(Platform platform, int i) {
        mShareHandler.sendEmptyMessage(AppContances.HANDLER_SHARE_CANCEL);
    }

    /**
     * 重新该类，开户跟客服的界面不显示福利小弹窗的广告哟~~
     */
    @Override
    public void showNoviceWelfare(String title, String link) {
        if (!TextUtils.isEmpty(key)) {
            if (key.equals(ConfigType.QQ_SERVICE_TAG) ||
                    key.equals(ConfigType.QUOTE_CONTACT_TAG) ||
                    key.equals(ConfigType.MY_CONTACT_TAG) ||
                    key.equals(ConfigType.HOME_CONTACT_TAG)) {
                return;
            }
        }
        super.showNoviceWelfare(title, link);
    }

}
